const MsgProto = {
  //ping消息
  PING_PROTO: 1001,
  //pong消息
  PONG_PROTO: 1002,
  //系统消息
  SYST_PROTO: 1003,
  //错误消息
  EROR_PROTO: 1004,
  //认证消息
  AUTH_PROTO: 1005,
  //普通消息
  MESS_PROTO: 1006,
  queueSocketTask: {},
  currentTabar: {},
  SocketTask: null,
  buildPingProto() {
    // console.log("发送 ping 消息！")
    return this.buildProto(this.PING_PROTO, null);
  },
  buildPongProto() {
    console.log("发送 pong 消息！")
    return this.buildProto(this.PONG_PROTO, null);
  },
  buildSystemProto(body) {
    console.log("发送 system 消息！" + JSON.stringify(body))
    return this.buildProto(this.SYST_PROTO, body);
  },
  buildMessProto(msg) {
    console.log("发送普通消息！" + JSON.stringify(body))
    let app = getApp()

  
    let body = msg
    console.log("body", body)
    return this.buildProto(this.MESS_PROTO, body);
  },
  buildProto(code, body) {
    let msgProto = {
      key: "client_bind",
      data: body,
      timestamp: new Date().getTime(),
    };
    console.log("msgProto", msgProto)
    return JSON.stringify(msgProto);
  },
  buildResponseProto(res) {
    return JSON.parse(res.data);
  },
  setUnReadCountFromGroups: function(that, list_news) {
    let unReadCountArray = list_news.map(g => {
      return g.unReadCount
    })
    let totalUnReadCount = unReadCountArray.reduce(function(prev, curr, idx, unReadCountArray) {
      return prev + curr;
    });
    let app = getApp()
    app.globalData.msgsCount = totalUnReadCount
    this.initUnReadCount()
  },
  addUnReadCount: function(msgProto) {
    let app = getApp()

    if (msgProto.body.id > app.globalData.currentMsgId) {
      app.globalData.currentMsgId = msgProto.body.id
      app.globalData.msgsCount = app.globalData.msgsCount + 1
      app.globalData.tabarList.forEach(t => {
        t.setData({
          msgsCount: app.globalData.msgsCount
        })
      })
    }

  },
  initUnReadCount: function() {
    let app = getApp()
    app.globalData.tabarList.forEach(t => {
      t.setData({
        msgsCount: app.globalData.msgsCount
      })
    })
  },
  autoRefreshMsg(key, curPage, callback) {
    let st = MsgProto.queueSocketTask[key]
    if (st) {
      MsgProto.queueSocketTask[key] = curPage
      return
    }
    MsgProto.queueSocketTask[key] = curPage

    MsgProto.SocketTask.onMessage((res) => {
      //收到消息
      let msgProto = MsgProto.buildResponseProto(res);
      let code = msgProto.code;
      switch (code) {
        case MsgProto.MESS_PROTO:
          //处理数据
          console.log("userMsg", msgProto)
          callback(msgProto.body, MsgProto.queueSocketTask[key])
          break;
        default:
          break;
      }
    })
  },
  sendMsg(msg) {
    let sendMsg = this.buildMessProto(msg)
    let app = getApp()
    loadProtoData(sendMsg)
    wx.sendSocketMessage({
      data: stringToUint8Array(sendMsg),
      success() {
        console.log("发送" + sendMsg + "成功");
      
      },
      fail() {
        app.show_("通讯服务断开，正在重连...")
        this.linkSocket()
      }
    });

  },
  heartCheck: {
    timeout: 10000,
    timeoutObj: null,
    serverTimeoutObj: null,
    reset: function() {
      clearTimeout(this.timeoutObj);
      clearTimeout(this.serverTimeoutObj);
      return this;
    },
    start: function() {
      this.timeoutObj = setTimeout(() => {
        MsgProto.SocketTask.send({
          data: MsgProto.buildPingProto(),
          success() {
            // console.log("发送ping成功");
          }
        });
        this.serverTimeoutObj = setTimeout(() => {
          MsgProto.SocketTask.close();
        }, this.timeout);
      }, this.timeout);
    }
  },
  linkSocket() {
    let app = getApp()
    let that = this
    // let time = new Date().getTime();
    let SocketTask = wx.connectSocket({
      url: app.globalData.socketUrl + '?code=1005' + '&token=' + app.globalData.data.token,
      success() {
        console.log('连接成功')
      }
    })
    MsgProto.SocketTask = SocketTask
    that.initEventHandle()
  },
  initEventHandle() {
    let app = getApp()
    let that = this
    MsgProto.SocketTask.onMessage((res) => {
      //收到消息
      let msgProto = MsgProto.buildResponseProto(res);
      let code = msgProto.code;

      switch (code) {
        case MsgProto.PING_PROTO:
        case MsgProto.PONG_PROTO:
          // console.log("code", code)
          MsgProto.heartCheck.reset().start()
          break;
        case MsgProto.SYST_PROTO:

          break;
        case MsgProto.EROR_PROTO:

          break;
        case MsgProto.AUTH_PROTO:
          console.log("AUTH_PROTO", "连接成功！")
          MsgProto.heartCheck.reset().start()
          break;
        case MsgProto.MESS_PROTO:
          //处理数据
          this.addUnReadCount(msgProto)
          console.log("init msg", msgProto)
          break;
        default:
          break;
      }
    })
    MsgProto.SocketTask.onOpen(() => {
      console.log('WebSocket连接打开')
      MsgProto.heartCheck.reset().start()
    })
    MsgProto.SocketTask.onError((res) => {
      console.log('WebSocket连接打开失败')
      this.reconnect()
    })
    MsgProto.SocketTask.onClose((res) => {
      console.log('WebSocket 已关闭！')
      MsgProto.queueSocketTask = {}
      this.reconnect()
    })
  },
  limit: 0,
  reconnect() {
    if (this.lockReconnect) return;
    this.lockReconnect = true;
    clearTimeout(this.timer)
    if (MsgProto.limit < 12) {
      this.timer = setTimeout(() => {
        this.linkSocket();
        this.lockReconnect = false;
      }, 5000);
      MsgProto.limit += 1
    }
  },
  closeConnect() {
    clearTimeout(this.timer)
  },

}
function objToStrMap(obj) {
  let strMap = new Map();
  for (let k of Object.keys(obj)) {
    strMap.set(k, obj[k]);
  }
  return strMap;
}

function stringToUint8Array(str) {
  var arr = [];
  for (var i = 0, j = str.length; i < j; ++i) {
    arr.push(str.charCodeAt(i));
  }

  var tmpUint8Array = new Uint8Array(arr);

  return tmpUint8Array
}
function  loadProtoData(data){


  var protobuf = require('protobuf.js'); //引入protobuf模块
  var HallLoginMessage = require('SentBody.js');//加载awesome.proto对应的json
  console.log("HallLoginMessage-", HallLoginMessage);
  var AwesomeRoot = protobuf.Root.fromJSON(HallLoginMessage);
  console.log("AwesomeRoot-", AwesomeRoot);
  var LoginRequest = AwesomeRoot.lookupType("SentBody");//这就是我们的Message类
  console.log("LoginRequest-", LoginRequest);
  var payload = data;
  var message = LoginRequest.create(payload);
  console.log("message-", message);
  var buffer = LoginRequest.encode(message).finish();
  console.log("buffer", buffer);
  var arrayBuffer = new ArrayBuffer(4 + buffer.length);
  var dataView = new DataView(arrayBuffer);
  dataView.setInt32(0, 10001);
  for (var i = 0; i < buffer.length; i++) {
    dataView.setUint8(i + 4, buffer[i]);
  }
  //console.log("dataView", dataView);
  console.log("发送的数据---", arrayBuffer);
}
module.exports = {
  MsgProto: MsgProto
}